package com.sc.nft.controller;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sc.nft.annotation.UserLogin;
import com.sc.nft.controller.request.CollectionPageRequest;
import com.sc.nft.controller.request.ConsensusAreaExitRequest;
import com.sc.nft.controller.request.ConsensusChangeRequest;
import com.sc.nft.dao.*;
import com.sc.nft.dto.UserCollectionConsensusVO;
import com.sc.nft.controller.vo.UserConsensusLogVO;
import com.sc.nft.entity.*;
import com.sc.nft.enums.UserConsensusTypeEnums;
import com.sc.nft.exception.GlobalException;
import com.sc.nft.exception.GlobalRunTimeException;
import com.sc.nft.mapper.UserCollectionConsensusMapper;
import com.sc.nft.pool.UserPool;
import com.sc.nft.service.UserConsensusService;
import com.sc.nft.sup.PageRequest;
import com.sc.nft.sup.PageResult;
import com.sc.nft.sup.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;


@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/consensus")
@Api(tags = "共识区")
public class ConsensusAreaController {

    private final ExitConsensusUserDao exitConsensusUserDao;
    private final UserConsensusDao userConsensusDao;
    private final UserCollectionConsensusDao userCollectionConsensusDao;
    private final CollectionConsensusDao collectionConsensusDao;
    private final UserConsensusService userConsensusService;
    private final UserConsensusLogDao userConsensusLogDao;
    private final UserCollectionConsensusMapper userCollectionConsensusMapper;
    private final StaticDataDao staticDataDao;


    private Date exitTime = DateTime.of("2024-08-26 18:00:00" , "yyyy-MM-dd HH:mm:ss");

    @ApiOperation(value = "退出共识区", notes = "退出共识区", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping(value = "/exit", produces = MediaType.APPLICATION_JSON_VALUE)
    @UserLogin
    public Result exit(@RequestBody ConsensusAreaExitRequest request) throws GlobalException {
        UserInfo user = UserPool.getUser();
        if(user.getCreateTime().after(exitTime)){
            return Result.fail("该用户不允许此操作");
        }
        if (!request.getPaymentPassword().equals(user.getTransactionPassword())) {
            throw new GlobalRunTimeException("支付密码错误");
        }
        ExitConsensusUser exitConsensusUser = exitConsensusUserDao.getByUserId(user.getId());
        if(ObjectUtil.isNull(exitConsensusUser)) {
            exitConsensusUser = new ExitConsensusUser();
            exitConsensusUser.setUserId(user.getId());
            exitConsensusUser.setStatus(true);
            exitConsensusUser.setNextApplyTime(DateTime.now().offset(DateField.MONTH,1));
            exitConsensusUser.insert();
        }else{
            if(exitConsensusUser.getStatus()){
                return Result.fail("您不在生态共识区中");
            }else{
                exitConsensusUser.setStatus(true);
                exitConsensusUser.setNextApplyTime(DateTime.now().offset(DateField.MONTH,1));
                exitConsensusUser.updateById();
            }
        }
        return Result.success();
    }


    @ApiOperation(value = "查询共识度", notes = "查询共识度", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping(value = "/findNum", produces = MediaType.APPLICATION_JSON_VALUE)
    @UserLogin
    public Result<String> findNum( ) throws GlobalException {
        UserInfo user = UserPool.getUser();

        ExitConsensusUser exitConsensusUser = exitConsensusUserDao.getByUserId(user.getId());
        if(ObjectUtil.isNotNull(exitConsensusUser)&&exitConsensusUser.getStatus()) {
            return Result.fail("您不在生态共识区中");
        }else{
            UserConsensus userConsensus = userConsensusDao.getUserConsensus(user.getId());
            return Result.success(userConsensus.getConsensusNum().toPlainString());
        }
    }



    @ApiOperation(value = "查询记录", notes = "查询记录", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping(value = "/recordPage", produces = MediaType.APPLICATION_JSON_VALUE)
    @UserLogin
    public PageResult<UserConsensusLogVO> recordPage(@RequestBody CollectionPageRequest request) throws GlobalException {
        UserInfo user = UserPool.getUser();
        Page<UserConsensusLog> page = userConsensusLogDao.getPage(user.getId(),request.getCollectionId()!=null?request.getCollectionId():0L ,request.toMp());
        Page<UserConsensusLogVO> result = new Page<>(page.getCurrent(),page.getSize(),page.getTotal());
        List<UserConsensusLogVO> list = Lists.newArrayList();
        for (UserConsensusLog record : page.getRecords()) {
            UserConsensusLogVO userConsensusLogVO = new UserConsensusLogVO();
            userConsensusLogVO.setConsensusNum(record.getConsensusNum().toPlainString());
            userConsensusLogVO.setRemark(record.getRemark());
            userConsensusLogVO.setAfterNum(record.getAfterNum().toPlainString());
            userConsensusLogVO.setBeforeNum(record.getBeforeNum().toPlainString());
            userConsensusLogVO.setCreateTime(record.getCreateTime());
            list.add(userConsensusLogVO);
        }
        result.setRecords(list);
        return PageResult.success(result);

    }


    @ApiOperation(value = "共识度展示列表", notes = "共识度展示列表", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping(value = "/consensusPage", produces = MediaType.APPLICATION_JSON_VALUE)
    @UserLogin
    public PageResult<UserCollectionConsensusVO> consensusPage(@RequestBody PageRequest request) throws GlobalException {
        UserInfo user = UserPool.getUser();
        Page<UserCollectionConsensusVO> userConsensusPage = userCollectionConsensusMapper.getUserConsensusPage(request.toMp(), user.getId());
        return PageResult.success(userConsensusPage);
    }

    @ApiOperation(value = "通用共识度转出", notes = "通用共识度转出", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping(value = "/consensusChange", produces = MediaType.APPLICATION_JSON_VALUE)
    @UserLogin
    public Result consensusChange(@RequestBody ConsensusChangeRequest request) throws GlobalException {
        StaticData consensusChangeBtn = staticDataDao.getByType("consensus_change_btn");
        if(consensusChangeBtn!=null&&StrUtil.equals(consensusChangeBtn.getValue(),"0")){
            return Result.fail("共识度兑换暂未开启");
        }
        if(NumberUtil.isLessOrEqual(request.getConsensusNum(),BigDecimal.ZERO)){
            return Result.fail("兑换额度不正确");
        }
        if(!NumberUtil.equals(request.getConsensusNum().multiply(BigDecimal.valueOf(100)).remainder(BigDecimal.TEN),BigDecimal.ZERO) ){
            return Result.fail("兑换额度仅支持最多一位小数");
        }

        UserInfo user = UserPool.getUser();
        Assert.isTrue(StrUtil.equals(user.getTransactionPassword(), request.getDealPwd()), () -> new GlobalRunTimeException("支付密码不正确"));
        CollectionConsensus collectionConsensus = collectionConsensusDao.getByCollectionId(request.getCollectionId());
        if(ObjectUtil.isNull(collectionConsensus)){
            return Result.fail("该生态今日可转贡献度不足");
        }
        BigDecimal todaySumChange = userConsensusLogDao.getTodaySumChange(user.getId(), request.getCollectionId());
        if(NumberUtil.isGreater(todaySumChange.add(request.getConsensusNum()),collectionConsensus.getConsensusNum()) ){
            return Result.fail("该生态今日可转贡献度不足");
        }
        userConsensusService.adjustConsensusService(user.getId(),request.getCollectionId(),request.getConsensusNum(), UserConsensusTypeEnums.CHANGE_INTO,null,null);
        return Result.success();
    }

    public static void main(String[] args) {
        BigDecimal a = BigDecimal.valueOf(0.1);
        System.out.println(a.multiply(BigDecimal.valueOf(100)).remainder(BigDecimal.TEN).equals(BigDecimal.ZERO));
    }
}